'use strict';

import CHINA_REGION from '../constants/region';
import React, { Component } from 'react';
import { Select } from 'antd';
import { Relax } from 'iflux2';

@Relax
export default class RegionCascader extends Component {
  static defaultProps = {
    selectItem: () => {}
  };

  constructor(props) {
    super(props);
    this.state = {
      provinceIndex: null,
      province: '',
      city: ''
    };
  }

  render() {
    let { provinceIndex, city, province } = this.state;
	  typeof provinceIndex === 'number' && console.log(CHINA_REGION[provinceIndex].children);
    return (
      <span>
        <Select showSearch style={{ width: 120 }} value={province} placeholder="请选择" onChange={this._changeProvince}>
          <Option value="">请选择</Option>
          {CHINA_REGION.map((item, index) => {
            return <Option value={item.name + ',' + index}>{item.label}</Option>;
          })}
        </Select>

        <Select
          showSearch
          style={{ width: 120, marginLeft: 20 }}
          placeholder="请选择"
          value={city}
          onChange={this._changeCity}
        >
          <Option value="">请选择</Option>
          {
            typeof provinceIndex === 'number'
            && CHINA_REGION[provinceIndex].children.length > 0
            ? CHINA_REGION[provinceIndex].children.map(item => <Option value={item.name}>{item.label}</Option>)
            : <Option value="">请选择</Option>}
        </Select>
      </span>
    );
  }

  _changeProvince = value => {
    let keys = this.props.keys;
    if (value) {
      let [province, index] = value.split(',');
      this.setState({ province: value, provinceIndex: parseInt(index), city: '' });
      this.props.selectItem({ value: province, key: keys.split(',')[0] },false);
      this.props.selectItem({ value: '', key: keys.split(',')[1] });
    } else {
      this.setState({ province: '', provinceIndex: null, city: '' });
      this.props.selectItem({ value: '', key: keys.split(',')[0] },false);
      this.props.selectItem({ value: '', key: keys.split(',')[1] });
    }
  };

  _changeCity = value => {
    this.setState({ city: value });
    let keys = this.props.keys;
    this.props.selectItem({ value, key: keys.split(',')[1] });
  };
}
